package com.woniu.controller;

import com.woniu.entity.Result;
import com.woniu.entity.dto.UserLoginDTO;
import com.woniu.entity.dto.UserUpdateDTO;
import com.woniu.pojo.User;
import com.woniu.service.UserService;
import com.woniu.utils.BaseController;
import com.woniu.utils.MobileUtil;
import com.woniu.utils.SMSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Api(tags = "用户控制类")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private String code;

    /**
     * 校验手机号是否被注册
     * @param
     * @return
     */
//    @ApiOperation("校验账号是否注册")
//    @PostMapping("/judgePhone/{phone}")
//    public Result judgePhone(@PathVariable String phone){
//         User user = userService.getByPhone(phone);
//         if (user != null){
//             return new Result(500,"手机号已被注册");
//         }
//        return new Result(200,"手机号未注册");
//    }

    @ApiOperation("注册接口")
    @PostMapping("/register")
    public Result Register(@RequestBody UserLoginDTO loginUserDTO){
        // 1. 对数据进行规则校验
        if (!MobileUtil.checkPhone(loginUserDTO.getPhone())){
            return new Result(500,"手机号码格式错误");
        }
        // 校验手机号码是否被注册
        User user = userService.getByPhone(loginUserDTO.getPhone());
        if (user != null){
            return new Result(500,"手机号已被注册");
        }
        // 2. 校验短信验证码
        // 2.1 从session中获取短信验证码
        String sessionCode = stringRedisTemplate.opsForValue().get("register_code_" + loginUserDTO.getPhone());
        // 2.2 比较
        if (sessionCode == null){
            return new Result(500,"请输入验证码");
        }
        if (!sessionCode.equalsIgnoreCase(loginUserDTO.getCode())){
            return new Result(500, "验证码输入不正确");
        }
//        if (loginUserDTO.getCode() == null ||loginUserDTO.getCode().length() == 0){
//            return new Result(500,"请输入验证码");
//        }
//        if (!code.equalsIgnoreCase(loginUserDTO.getCode())){
//            return new Result(500, "验证码输入不正确");
//        }
        try {
            userService.register(loginUserDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(500, "注册失败");
        }
        //清除验证码
        stringRedisTemplate.delete("register_code_" + loginUserDTO.getPhone());
        return new Result(200, "注册成功");
    }
    /**
     * 发送短信
     * @param phone
     * @return
     */
    @ApiOperation("发送短信")
    @GetMapping("/sendSms/{phone}")
    public Result sendSms(@PathVariable String phone){
        //手机号码校验
        if (!MobileUtil.checkPhone(phone)){
            return new Result(500,"手机号码格式错误");
        }
        // 需求1：短信验证码的有效期是5分钟，如果短信验证码没有被使用，那么5分钟之内不能重复发送短信
        // 判断该key在redis中是否存在
        String redis_code = stringRedisTemplate.opsForValue().get("register_code_" + phone);
        if (!StringUtils.isEmpty(redis_code)){
            return new Result(500,"验证码已经发送，请勿重新发送");
        }
        //获取该账号验证码发送次数，到了五次 禁止发送
        String redisCodeCount = stringRedisTemplate.opsForValue().get("register_code_" + phone + "_count");
        if ("5".equalsIgnoreCase(redisCodeCount)){
            return new Result(500,"您今天已经发送太多短信，请换个时间或改用其他验证方式");
        }
        // 3. 发送短信
        // 3.1 生成一个验证码
        code = SMSUtils.getRandomNum(4);
        System.out.println("code ===================================== " + code);
        // 3.2 发送短信
        // SMSUtils.sendSms(phone,code);
        // 保存验证码，此处的key应该保持每一个场景是唯一的
        stringRedisTemplate.opsForValue().set("register_code_"+ phone,code,60, TimeUnit.SECONDS);
        // 在redis中记录该场景，该手机号码发了多少条短信
        // 1. 获取次数
        if (StringUtils.isEmpty(redisCodeCount)){
            stringRedisTemplate.opsForValue().set("register_code_" + phone + "_count","1");
        }else {
            stringRedisTemplate.opsForValue().set("register_code_" + phone + "_count",Integer.parseInt(redisCodeCount) + 1 + "");
        }
        // 4. 响应result
        return new Result(200, "验证码发送成功");
    }

    /**
     * 登录页面的登录操作
     * @param loginUserDTO
     * @param session
     * @return
     */
    @ApiOperation("登录接口")
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody UserLoginDTO loginUserDTO, HttpSession session){
        System.out.println("loginUserDTO.getMobile() = " + loginUserDTO.getPhone());
        // 1. 对数据进行规则校验
        if (!MobileUtil.checkPhone(loginUserDTO.getPhone())){
            return new Result(500,"手机号码格式错误");
        }
        // 2. 校验短信验证码
        // 2.1 从session中获取短信验证码
        String sessionCode = stringRedisTemplate.opsForValue().get("register_code_" + loginUserDTO.getPhone());
        // 2.2 比较
        if (sessionCode == null){
            return new Result(500,"您还没有登录，请登录！");
        }
        if (!sessionCode.equalsIgnoreCase(loginUserDTO.getCode())){
            return new Result(500, "验证码输入不正确");
        }

        // 3. 查询数据库中是否存在该手机号码
        User user = userService.getByPhone(loginUserDTO.getPhone());

        // 4. 不存在，登录失败
        if (user == null){
            return new Result(500, "用户不存在！");
        }

        // 5. 存在，需要保存登录状态（session）
        session.setAttribute("login_user",user);
        //设置登录时间
        userService.setLoginTime(loginUserDTO.getPhone());
        // 6. 清除短信验证码（重要）
        stringRedisTemplate.delete("register_code_" + loginUserDTO.getPhone());
        // 7. 响应数据
        return new Result(200,"登陆成功");
    }
    @ApiOperation("修改密码")
    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody UserUpdateDTO userUpdateDTO){
       if (userUpdateDTO.getOldPwd() == null || userUpdateDTO.getOldPwd().trim().length()==0){
           return new Result(500,"请输入旧密码");
       }
        if (userUpdateDTO.getNewPwd() == null || userUpdateDTO.getNewPwd() .trim().length()==0){
            return new Result(500,"请输入新密码");
        }
       User user = userService.checkOldPwd(userUpdateDTO.getUserId(),userUpdateDTO.getOldPwd());
       if (user == null){
           return new Result(500,"旧密码错误,请重新输入");
       }
       boolean flag = userService.updatePwd(userUpdateDTO.getUserId(),userUpdateDTO.getNewPwd());
       return toResult(flag);
    }
}
